{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts.chat import (\n",
    "    ChatPromptTemplate,\n",
    "    SystemMessagePromptTemplate,\n",
    "    HumanMessagePromptTemplate,\n",
    ")\n",
    "\n",
    "# 定义系统消息模板\n",
    "system_template = \"You are a helpful assistant that translates {input_language} to {output_language}.\"\n",
    "system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)\n",
    "\n",
    "# 定义用户消息模板\n",
    "human_template = \"{text}\"\n",
    "human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n",
    "\n",
    "# 组合系统消息和用户消息成一个聊天提示\n",
    "chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n",
    "\n",
    "print(chat_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 引入第三方大模型\n",
    "import os\n",
    "from langchain_community.chat_models import ChatTongyi\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "chat  = ChatTongyi(model='qwen-plus',\n",
    "                   top_p=0.9,\n",
    "                   temperature=0.9,\n",
    "                   api_key=os.getenv(\"DASHSCOPE_API_KEY\"))\n",
    "print(chat.invoke('你是谁？'))\n",
    "\n",
    "\n",
    "# 格式化聊天提示并获取模型响应\n",
    "response = chat(chat_prompt.format_prompt(\n",
    "    input_language=\"English\",\n",
    "    output_language=\"Chinese\",\n",
    "    text=\"Who i am.\"\n",
    ").to_messages())\n",
    "\n",
    "print(response)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "template = \"\"\"\n",
    "作为一个品牌宣传专家，请为以下品类进行宣传：\n",
    "{% if mood == \"手机\" %}\n",
    "请为以下产品的手机提供一个宣传方案{product}!\n",
    "{% elif mood == \"电脑\" %}\n",
    "请为以下产品的电脑提供一个宣传方案{product}!\n",
    "{% else %}\n",
    "请为以下产品供一个宣传方案{product}!\n",
    "{% endif %}\n",
    "\"\"\"\n",
    "# 创建 PromptTemplate 时指定 template_format 为 'jinja2'\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"手机\"],\n",
    "    template=template,\n",
    "    template_format='jinja2'\n",
    ")\n",
    "# 格式化聊天提示并获取模型响应\n",
    "response = chat(chat_prompt.format_prompt(\n",
    "    input_language=\"English\",\n",
    "    output_language=\"Chinese\",\n",
    "    text=\"Who i am.\"\n",
    ").to_messages())\n",
    "\n",
    "print(response)\n",
    "# 使用模板并传入参数\n",
    "formatted_prompt = prompt.format(mood=\"happy\")\n",
    "print(formatted_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.schema import HumanMessage\n",
    "# 引入第三方大模型\n",
    "import os\n",
    "from langchain_community.chat_models import ChatTongyi\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv()\n",
    "chat = ChatTongyi(\n",
    "    model='qwen-plus',\n",
    "    top_p=0.9,\n",
    "    temperature=0.9,\n",
    "    api_key=os.getenv(\"DASHSCOPE_API_KEY\")\n",
    ")\n",
    "\n",
    "template = \"\"\"\n",
    "作为一个品牌宣传专家，请为以下品类进行宣传：\n",
    "{% if category == \"手机\" %}\n",
    "请为以下{{ brand }}手机提供一个宣传方案：{{ product }}\n",
    "{% elif category == \"电脑\" %}\n",
    "请为以下{{ brand }}电脑提供一个宣传方案：{{ product }}\n",
    "{% else %}\n",
    "请为以下{{ brand }}{{ category }}提供一个宣传方案：{{ product }}\n",
    "{% endif %}\n",
    "\"\"\"\n",
    "\n",
    "# 创建 PromptTemplate 时指定 template_format 为 'jinja2'，并将 validate_template 设置为 False\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"category\", \"brand\", \"product\"],\n",
    "    template=template,\n",
    "    template_format='jinja2',\n",
    "    validate_template=False\n",
    ")\n",
    "\n",
    "# 设置品牌宣传的参数\n",
    "category = \"手机\"\n",
    "brand = \"iPhone\"\n",
    "product = \"iPhone 13 Pro Max\"\n",
    "\n",
    "# 格式化品牌宣传提示\n",
    "formatted_prompt = prompt.format(\n",
    "    category=category,\n",
    "    brand=brand,\n",
    "    product=product\n",
    ")\n",
    "\n",
    "# 将格式化后的提示包装为 HumanMessage，并传递给 chat()\n",
    "response = chat([HumanMessage(content=formatted_prompt)])\n",
    "\n",
    "print(response.content)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.schema import HumanMessage\n",
    "# 引入所需的模型，例如 OpenAI 的 ChatOpenAI\n",
    "import os\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "# 初始化聊天模型\n",
    "chat = ChatTongyi(\n",
    "    model='qwen-plus',\n",
    "    top_p=0.9,\n",
    "    temperature=0.9,\n",
    "    api_key=os.getenv(\"DASHSCOPE_API_KEY\")\n",
    ")\n",
    "\n",
    "# 定义模板，使用 Jinja2 的循环结构\n",
    "template = \"\"\"\n",
    "您好！\n",
    "\n",
    "我们正在进行一项调查，想请您回答以下问题：\n",
    "\n",
    "{% for question in questions %}\n",
    "{{ loop.index }}. {{ question }}\n",
    "{% endfor %}\n",
    "\n",
    "请您依次回答以上问题，非常感谢您的参与！\n",
    "\"\"\"\n",
    "\n",
    "# 创建 PromptTemplate，指定 template_format为'jinja2'，并将 validate_template 设置为 False\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"questions\"],\n",
    "    template=template,\n",
    "    template_format='jinja2',\n",
    "    validate_template=False\n",
    ")\n",
    "\n",
    "# 定义问题列表\n",
    "questions = [\n",
    "    \"您喜欢的手机是什么？\",\n",
    "    \"您的喜欢手机的价格段位在多少？\",\n",
    "    \"您的大概期手机的消费占一个月工资的比例是多少？\",\n",
    "    \"您最喜欢的手机颜色是什么？\",\n",
    "    \"您对手机改进任何建议吗？\"\n",
    "]\n",
    "\n",
    "# 格式化提示词\n",
    "formatted_prompt = prompt.format(questions=questions)\n",
    "\n",
    "# 将格式化后的提示包装为 HumanMessage，并传递给 chat()\n",
    "response = chat([HumanMessage(content=formatted_prompt)])\n",
    "\n",
    "# 打印模型的回复\n",
    "print(response.content)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.schema import HumanMessage\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import ConversationBufferMemory  # 导入内存模块\n",
    "from langchain.chat_models import ChatOpenAI  # 确保导入正确的模型\n",
    "import logging\n",
    "\n",
    "# 配置日志\n",
    "logging.basicConfig(level=logging.INFO, filename='report_generation.log',\n",
    "                    format='%(asctime)s - %(levelname)s - %(message)s')\n",
    "\n",
    "# 加载环境变量，例如 API 密钥\n",
    "load_dotenv()\n",
    "\n",
    "# 初始化内存\n",
    "memory = ConversationBufferMemory(\n",
    "    memory_key=\"history\",\n",
    "    return_messages=True\n",
    ")\n",
    "\n",
    "try:\n",
    "    # 初始化聊天模型\n",
    "    chat = ChatTongyi(\n",
    "        model='qwen-plus',\n",
    "        top_p=0.9,\n",
    "        temperature=0.9,\n",
    "        api_key=os.getenv(\"DASHSCOPE_API_KEY\")\n",
    "    )\n",
    "    logging.info(\"聊天模型初始化成功。\")\n",
    "except Exception as e:\n",
    "    logging.error(f\"聊天模型初始化失败: {e}\")\n",
    "    raise e\n",
    "\n",
    "# 初始化 ConversationChain\n",
    "chain = ConversationChain(\n",
    "    llm=chat,\n",
    "    memory=memory,\n",
    "    verbose=True  # 可选，启用详细日志\n",
    ")\n",
    "\n",
    "# 定义行业名称\n",
    "industry = \"新能源汽车\"\n",
    "\n",
    "# 定义通用提示模板\n",
    "inner_template = \"\"\"\n",
    "请撰写关于{industry}行业的“{section_name}”部分，内容应包括：\n",
    "{section_details}\n",
    "\n",
    "请确保内容详实且结构清晰，并引用最新的数据。\n",
    "\"\"\"\n",
    "\n",
    "inner_prompt = PromptTemplate.from_template(inner_template)\n",
    "\n",
    "# 定义每个章节的具体要求\n",
    "sections = {\n",
    "    \"行业概述\": \"\"\"\n",
    "- 行业定义\n",
    "- 当前市场规模\n",
    "- 主要驱动因素\n",
    "\"\"\",\n",
    "    \"市场趋势\": \"\"\"\n",
    "- 最新发展动态\n",
    "- 技术创新\n",
    "- 政策影响\n",
    "\"\"\",\n",
    "    \"竞争分析\": \"\"\"\n",
    "- 市场份额\n",
    "- 主要优势\n",
    "- 主要劣势\n",
    "- 最新战略动向\n",
    "\"\"\",\n",
    "    \"未来预测\": \"\"\"\n",
    "- 未来五年的市场预测\n",
    "- 潜在的市场机会和挑战\n",
    "\"\"\"\n",
    "}\n",
    "\n",
    "# 创建每个章节的提示内容\n",
    "prompts = {\n",
    "    section: inner_prompt.format(\n",
    "        industry=industry,\n",
    "        section_name=section,\n",
    "        section_details=details.strip()\n",
    "    )\n",
    "    for section, details in sections.items()\n",
    "}\n",
    "\n",
    "def generate_section(formatted_prompt: str, section_name: str) -> str:\n",
    "    \"\"\"\n",
    "    生成报告的一个部分。\n",
    "\n",
    "    :param formatted_prompt: 已格式化的提示内容\n",
    "    :param section_name: 报告部分名称\n",
    "    :return: 模型生成的内容\n",
    "    \"\"\"\n",
    "    try:\n",
    "        logging.info(f\"生成部分: {section_name}\")\n",
    "        logging.debug(f\"提示 '{section_name}': {formatted_prompt}\")\n",
    "        \n",
    "        # 使用 ConversationChain 生成响应\n",
    "        generated_content = chain.run(formatted_prompt).strip()\n",
    "        logging.info(f\"部分 '{section_name}' 生成成功。\")\n",
    "        \n",
    "        return generated_content\n",
    "    except Exception as e:\n",
    "        logging.error(f\"生成部分 '{section_name}' 时出错: {e}\")\n",
    "        return f\"生成部分 '{section_name}' 时出错: {e}\"\n",
    "\n",
    "def main():\n",
    "    report_sections = {}\n",
    "    for section, prompt in prompts.items():\n",
    "        report_sections[section] = generate_section(prompt, section)\n",
    "\n",
    "    # 组合完整报告\n",
    "    complete_report = f\"\"\"\n",
    "**市场分析报告：{industry}行业**\n",
    "\n",
    "1. **行业概述**\n",
    "   {report_sections.get(\"行业概述\", \"内容未生成。\")}\n",
    "\n",
    "2. **市场趋势**\n",
    "   {report_sections.get(\"市场趋势\", \"内容未生成。\")}\n",
    "\n",
    "3. **竞争分析**\n",
    "   {report_sections.get(\"竞争分析\", \"内容未生成。\")}\n",
    "\n",
    "4. **未来预测**\n",
    "   {report_sections.get(\"未来预测\", \"内容未生成。\")}\n",
    "\n",
    "请确保所有数据均来自可靠来源，并在报告中注明数据来源。\n",
    "\"\"\"\n",
    "\n",
    "    print(\"市场分析报告:\\n\")\n",
    "    print(complete_report)\n",
    "\n",
    "    # 可选择将报告保存到文件\n",
    "    try:\n",
    "        with open(\"市场分析报告.txt\", \"w\", encoding=\"utf-8\") as file:\n",
    "            file.write(complete_report)\n",
    "        logging.info(\"报告已成功保存到 '市场分析报告.txt'。\")\n",
    "    except Exception as e:\n",
    "        logging.error(f\"保存报告到文件时发生错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "chatchat",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
